package com.pet.comment.service.impl;

import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.pet.comment.service.ApCommentService;
import com.pet.comment.feign.ApUserFeign;
import com.pet.common.constants.MQConstants;
import com.pet.common.exception.LeadNewsException;
import com.pet.model.behavior.dtos.UpdateArticleMsg;
import com.pet.model.comment.dtos.ApCommentVo;
import com.pet.model.comment.dtos.CommentDto;
import com.pet.model.comment.dtos.CommentLikeDto;
import com.pet.model.comment.dtos.CommentSaveDto;
import com.pet.model.comment.pojos.ApComment;
import com.pet.model.comment.pojos.ApCommentLike;
import com.pet.model.common.dtos.ResponseResult;
import com.pet.model.common.enums.AppHttpCodeEnum;
import com.pet.model.user.pojos.ApUser;
import com.pet.utils.common.BeanHelper;
import com.pet.utils.common.JsonUtils;
import com.pet.utils.threadlocal.ThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ApCommentServiceImpl implements ApCommentService {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private ApUserFeign apUserFeign;
    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {
        //1.判断用户是否登录
        ApUser apUser= (ApUser) ThreadLocalUtils.get();
        if(apUser==null){
            throw new LeadNewsException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.判断评论内容长度不超过140字符
        if(StringUtils.isNotEmpty(dto.getContent())&&dto.getContent().length()>140){
            throw new LeadNewsException(400,"评论内容长度不能超过140个字");
        }

        try {
            //3.保存评论数据
            //查询当前用户信息
            apUser = apUserFeign.findOne(apUser.getId()).getData();

            ApComment apComment = new ApComment();
            apComment.setAuthorId(apUser.getId());
            apComment.setAuthorName(apUser.getName());
            apComment.setEntryId(dto.getArticleId());
            apComment.setType(0);
            apComment.setContent(dto.getContent());
            apComment.setImage(apUser.getImage());
            apComment.setLikes(0);
            apComment.setReply(0);
            apComment.setFlag(0);
            apComment.setOrd(1);
            apComment.setCreatedTime(new Date());

            mongoTemplate.save(apComment);

            //评论行为时发送MQ消息
            UpdateArticleMsg updateArticleMsg = new UpdateArticleMsg();
            updateArticleMsg.setType(UpdateArticleMsg.UpdateArticleType.COMMENT);
            updateArticleMsg.setArticleId(dto.getArticleId());

            kafkaTemplate.send(MQConstants.HOT_ARTICLE_INPUT_TOPIC,UUID.randomUUID().toString(), JsonUtils.toString(updateArticleMsg));

            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            throw new LeadNewsException(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

    @Override
    public ResponseResult<Map<String, Object>> likeComment(CommentLikeDto dto) {
        //1.判断用户是否登录
        ApUser apUser = (ApUser) ThreadLocalUtils.get();
        if(apUser==null){
            throw new LeadNewsException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.判断是否存在当前评论的点赞数据，再判断是否点赞还是取消点赞
        //查询当前用户对当前评论点赞记录
        Query query = Query.query(Criteria.where("authorId").is(apUser.getId()).and("commentId").is(dto.getCommentId()));
        List<ApCommentLike> apCommentLikes = mongoTemplate.find(query, ApCommentLike.class);
        if(CollectionUtils.isEmpty(apCommentLikes)&&dto.getOperation().equals(0)){
            //2.1 点赞操作，新增评论点赞数据，更新评论的likes+1

            //新增评论点赞记录
            ApCommentLike apCommentLike = new ApCommentLike();
            apCommentLike.setAuthorId(apUser.getId());
            apCommentLike.setCommentId(dto.getCommentId());
            apCommentLike.setOperation(0);
            mongoTemplate.save(apCommentLike);
            //更新评论的likes+1
            Query commentQuery = Query.query(Criteria.where("_id").is(dto.getCommentId()));
            Update update = new Update();
            update.inc("likes");
            mongoTemplate.updateMulti(commentQuery,update,ApComment.class);
        }else {
            //2.2 取消点赞操作，删除评论点赞数据，更新评论的likes-1

            //删除评论点赞记录
            mongoTemplate.remove(query,ApCommentLike.class);
            //更新评论的likes-1
            Query commentQuery = Query.query(Criteria.where("_id").is(dto.getCommentId()));
            Update update = new Update();
            update.inc("likes",-1);
            mongoTemplate.updateMulti(commentQuery,update,ApComment.class);
        }
        //查询最新评论的点赞数
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        Map<String, Object> map = new HashMap<>();
        map.put("likes",apComment.getLikes());
        return ResponseResult.okResult(map);
    }

    @Override
    public ResponseResult<List> loadComment(CommentDto dto) {
        if(dto.getMinDate()==null)dto.setMinDate(new Date());
        //1.先根据条件（查询条件+分页+排序）查询评论数据
        //1）封装条件
        Query query = Query.query(Criteria.where("entryId").is(dto.getArticleId()).and("createdTime").lt(dto.getMinDate()));
        //2）分页  排序   先按照评论点赞数倒序，再按照创建时间倒序
        query.limit(10);
        query.with(Sort.by(Sort.Direction.DESC,"likes"));
        query.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        //4）查询数据
        List<ApComment> commentList = mongoTemplate.find(query, ApComment.class);
        //2.如果当前用户没有登录，直接返回查询结果即可
        ApUser apUser = (ApUser) ThreadLocalUtils.get();
        if(apUser==null){
            return ResponseResult.okResult(commentList);
        }
        //3.如果当前用户已登录，判断当前用户对哪些评论点赞过，对点赞过的评论添加operation为0的属性
        //1）根据用户ID和评论ID查询评论点赞记录
        List<String> idList = commentList.stream().map(ApComment::getId).collect(Collectors.toList());
        Query likeQuery = Query.query(Criteria.where("authorId").is(apUser.getId()).and("commentId").in(idList));
        List<ApCommentLike> likeList = mongoTemplate.find(likeQuery, ApCommentLike.class);
        //2）遍历commentList
        List<ApCommentVo> apCommentVoList = new ArrayList<>();
        commentList.forEach(comment -> {
            //3）找出commentList中每个评论的id是否和  点赞记录列表的评论ID 相同的记录
           /* for(ApCommentLike like:likeList){
                if(like.getCommentId().equals(comment.getId())){

                }
            }*/

            //拷贝数据
            ApCommentVo apCommentVo = BeanHelper.copyProperties(comment, ApCommentVo.class);
            long count = likeList.stream().filter(apCommentLike ->
                    apCommentLike.getCommentId().equals(comment.getId())).count();
            if (count>0){
                //4）给上一步找出来的评论对象添加operation=0属性
                apCommentVo.setOperation(0);
            }
            apCommentVoList.add(apCommentVo);
        });
        return ResponseResult.okResult(apCommentVoList);
    }
}
